/*
    Matali Physics Demo
    Copyright (c) 2011 KOMIRES Sp. z o. o.
 */
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Komires.MataliPhysics;

namespace MySimpleScene
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class DemoMesh
    {
        Game1 demo;
        VertexBuffer meshVertexBuffer;
        IndexBuffer meshIndexBuffer;
        Texture2D meshTexture;
        RasterizerState meshCullMode;
        int triangleCount;
        int vertexCount;
        int indexCount;

        Texture2D background;

        VertexPositionNormalTexture[] meshVertices;
        ushort[] meshIndices16Bit;
        int[] meshIndices32Bit;

        public VertexPositionNormalTexture[] Vertices { get { return meshVertices; } }
        public ushort[] Indices16Bit { get { return meshIndices16Bit; } }
        public int[] Indices32Bit { get { return meshIndices32Bit; } }

        public Model Model;
        public BasicEffect Effect;

        Vector3 ambient;
        Vector3 diffuse;
        Vector3 emission;
        Vector3 specular;

        public DemoMesh(Game1 demo)
        {
            this.demo = demo;
            Effect = new BasicEffect(demo.GraphicsDevice);
            meshVertexBuffer = null;
            meshIndexBuffer = null;
            meshVertices = null;
            meshIndices16Bit = null;
            meshIndices32Bit = null;
            meshCullMode = RasterizerState.CullClockwise;

            SetTexture(null);
        }

        public DemoMesh(Game1 demo, Model model)
        {
            this.demo = demo;
            this.Model = model;
            Effect = new BasicEffect(demo.GraphicsDevice);
            meshVertexBuffer = null;
            meshIndexBuffer = null;
            meshVertices = null;
            meshIndices16Bit = null;
            meshIndices32Bit = null;
            meshCullMode = RasterizerState.CullClockwise;

            SetTexture(null);
        }

        public DemoMesh(Game1 demo, Shape shape, Texture2D texture, Vector2 textureScale, bool flipTriangles, bool flipNormals, bool smoothNormals, RasterizerState cullMode)
        {
            this.demo = demo;
            Model = null;
            Effect = new BasicEffect(demo.GraphicsDevice);
            meshVertexBuffer = null;
            meshIndexBuffer = null;
            meshVertices = null;
            meshIndices16Bit = null;
            meshIndices32Bit = null;

            SetCullMode(cullMode);
            SetTexture(texture);

            shape.GetMesh(textureScale, flipTriangles, flipNormals, smoothNormals, out meshVertices);
            CreateVertexBuffer(meshVertices, false);
        }

        public DemoMesh(Game1 demo, TriangleMesh triangleMesh, Texture2D texture, Vector2 textureScale, bool indices, bool indices16Bit, bool flipTriangles, bool flipNormals, bool smoothNormals, RasterizerState cullMode)
        {
            this.demo = demo;
            Model = null;
            Effect = new BasicEffect(demo.GraphicsDevice);
            meshVertexBuffer = null;
            meshIndexBuffer = null;
            meshVertices = null;
            meshIndices16Bit = null;
            meshIndices32Bit = null;

            SetCullMode(cullMode);
            SetTexture(texture);

            if (indices)
            {
                triangleMesh.GetMeshVertices(flipNormals, smoothNormals, out meshVertices);
                CreateVertexBuffer(meshVertices, false);

                if (indices16Bit)
                {
                    triangleMesh.GetMeshIndices(flipTriangles, out meshIndices16Bit);
                    CreateIndexBuffer(meshIndices16Bit, false);
                }
                else
                {
                    triangleMesh.GetMeshIndices(flipTriangles, out meshIndices32Bit);
                    CreateIndexBuffer(meshIndices32Bit, false);
                }
            }
            else
            {
                triangleMesh.GetMesh(textureScale, flipTriangles, flipNormals, smoothNormals, out meshVertices);
                CreateVertexBuffer(meshVertices, false);
            }
        }

        public void CreateVertexBuffer(VertexPositionNormalTexture[] vertices, bool dynamic)
        {
            if (vertices.Length == 0) return;

            Model = null;

            if (dynamic)
                meshVertexBuffer = new DynamicVertexBuffer(demo.GraphicsDevice, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
            else
                meshVertexBuffer = new VertexBuffer(demo.GraphicsDevice, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);

            meshVertexBuffer.SetData<VertexPositionNormalTexture>(vertices);


            meshVertices = vertices;
            vertexCount = vertices.Length;
            triangleCount = vertexCount / 3;
        }

        public void CreateIndexBuffer(ushort[] indices, bool dynamic)
        {
            if (indices.Length == 0) return;

            Model = null;

            if (dynamic)
                meshIndexBuffer = new DynamicIndexBuffer(demo.GraphicsDevice, IndexElementSize.SixteenBits, indices.Length, BufferUsage.WriteOnly);
            else
                meshIndexBuffer = new IndexBuffer(demo.GraphicsDevice, IndexElementSize.SixteenBits, indices.Length, BufferUsage.WriteOnly);

            meshIndexBuffer.SetData<ushort>(indices);

            meshIndices16Bit = indices;
            indexCount = indices.Length / 3;
        }

        public void CreateIndexBuffer(int[] indices, bool dynamic)
        {
            if (indices.Length == 0) return;

            Model = null;

            if (dynamic)
                meshIndexBuffer = new DynamicIndexBuffer(demo.GraphicsDevice, IndexElementSize.ThirtyTwoBits, indices.Length, BufferUsage.WriteOnly);
            else
                meshIndexBuffer = new IndexBuffer(demo.GraphicsDevice, IndexElementSize.ThirtyTwoBits, indices.Length, BufferUsage.WriteOnly);

            meshIndexBuffer.SetData<int>(indices);

            meshIndices32Bit = indices;
            indexCount = indices.Length / 3;
        }

        public void SetVertices(VertexPositionNormalTexture[] vertices)
        {
            meshVertexBuffer.SetData<VertexPositionNormalTexture>(vertices);

            meshVertices = vertices;
            vertexCount = vertices.Length;
            triangleCount = vertexCount / 3;
        }

        public void SetIndices(ushort[] indices)
        {
            meshIndexBuffer.SetData<ushort>(indices);

            meshIndices16Bit = indices;
            indexCount = indices.Length / 3;
        }

        public void SetIndices(int[] indices)
        {
            meshIndexBuffer.SetData<int>(indices);

            meshIndices32Bit = indices;
            indexCount = indices.Length / 3;
        }

        public void SetTexture(Texture2D texture)
        {
            meshTexture = texture;

            if (texture != null)
            {
                Effect.TextureEnabled = true;
                Effect.Texture = texture;
            }
            else
            {
                Effect.TextureEnabled = false;
                Effect.Texture = null;
            }
        }

        public void SetCullMode(RasterizerState cullMode)
        {
            meshCullMode = cullMode;
        }

        public void Draw(PhysicsMaterial material, bool sleep)
        {
            if (Model == null)
            {
                demo.GraphicsDevice.RasterizerState = meshCullMode;

                Texture2D currentTexture = meshTexture;
                if (material.UserTagStr != null)
                    currentTexture = demo.Textures[material.UserTagStr];

                material.GetAmbient(ref ambient);
                material.GetDiffuse(ref diffuse);
                material.GetEmission(ref emission);
                material.GetSpecular(ref specular);

                if (sleep)
                {
                    diffuse.X = 0.7f;
                    diffuse.Y = 1.0f;
                    diffuse.Z = 1.0f;
                }

                Effect.AmbientLightColor = ambient;
                Effect.DiffuseColor = diffuse;
                Effect.SpecularColor = specular;
                Effect.EmissiveColor = emission;
                Effect.SpecularPower = material.SpecularPower;
                Effect.Alpha = material.TransparencyFactor;

                if (currentTexture != null)
                {
                    Effect.TextureEnabled = true;
                    Effect.Texture = currentTexture;
                }
                else
                {
                    Effect.TextureEnabled = false;
                    Effect.Texture = null;
                }

                if (meshVertexBuffer != null)
                {
                    if (meshIndexBuffer != null)
                    {
                        demo.GraphicsDevice.SetVertexBuffer(meshVertexBuffer);
                        demo.GraphicsDevice.Indices = meshIndexBuffer;

                        Effect.Techniques[0].Passes[0].Apply();

                        demo.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexCount, 0, indexCount);
                    }
                    else
                    {
                        demo.GraphicsDevice.SetVertexBuffer(meshVertexBuffer);

                        Effect.Techniques[0].Passes[0].Apply();

                        demo.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, triangleCount);
                    }
                }
            }
        }
    }
}
